package com.whpost.service.wx.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.config.Wdpz;
import com.whpost.service.dao.t.TCzyDao;
import com.whpost.service.dao.t.TRegionDao;
import com.whpost.service.dao.t.TRoleDao;
import com.whpost.service.dao.t.TXzjgDao;
import com.whpost.service.entity.t.TCzy;
import com.whpost.service.entity.t.TRegion;
import com.whpost.service.entity.t.TRole;
import com.whpost.service.entity.t.TXzjg;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.service.BaseServices;
import com.whpost.service.service.WxBaseServices;
import com.whpost.service.service.t.FileService;
import com.whpost.service.service.t.TApiNonceService;
import com.whpost.service.tools.ToolBean;
import com.whpost.service.tools.Url;
import com.whpost.service.wx.dao.*;
import com.whpost.service.wx.entiy.*;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by IntelliJ IDEA.
 *
 * @Author: Yin Zhuoyi
 * @Date: 2021/12/15 11:16
 */
@Service
public class BaomingServices extends WxBaseServices<WxBaomingMapper, WxBaoming> {

    @Resource
    private WxXxlyMapper wxXxlyMapper;
    @Resource
    private WxCyxxMapper wxCyxxMapper;
    @Resource
    private WxBslxMapper wxBslxMapper;
    @Resource
    private TApiNonceService tApiNonceService;
    @Resource
    private TXzjgDao tXzjgDao;
    @Resource
    private TRegionDao tRegionDao;
    @Resource
    private WxBaomingCyxxMapper wxBaomingCyxxMapper;
    @Resource
    private WxBaomingTjMapper wxBaomingTjMapper;
    @Resource
    private Wdpz wdpz;
    @Resource
    private FileService fileService;

    @Override
    public ResultInfo info(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String id="";
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            String lx="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }

            Map<String,Object> infoMap = new HashMap<>();

            //信息来源
            List<WxXxly> wxXxlyList = wxXxlyMapper.selectList(null);

            //比赛类型
            List<WxBslx> wxBslxList = wxBslxMapper.selectList(null);

            //邮政网点
            List<TXzjg> tXzjgList = tXzjgDao.selectList(new QueryWrapper<TXzjg>().eq("id","5"));

            //省
            List<TRegion> tRegionList = tRegionDao.selectList(new QueryWrapper<TRegion>().eq("jb","1"));

            //成员信息
            List<WxCyxx> wxCyxxList = wxCyxxMapper.selectList(new QueryWrapper<WxCyxx>().eq("hyxx_lsh",loginId));

            WxBaoming wxBaoming = new WxBaoming();

            infoMap.put("wxXxlyList",wxXxlyList);
            infoMap.put("wxBslxList",wxBslxList);
            infoMap.put("tXzjgList",tXzjgList);
            infoMap.put("tRegionList",tRegionList);
            infoMap.put("wxCyxxList",wxCyxxList);
            infoMap.put("lx",lx);
            infoMap.put("id",id);
            infoMap.put("wxBaoming",wxBaoming);
            ResultInfo resultInfo = new ResultInfo(200, "成功返回！",infoMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    @Transactional
    public ResultInfo save(String loginId, List<MultipartFile> file,String data) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{

            JSONObject jsonObject = getDataStr(data,loginId);

            ToolBean.info("获取的数据:"+jsonObject);
            // 将JSON字符串转换为Java对象
            BaoMingSubmitData submitData = JSON.parseObject(jsonObject.getString("submitData"), BaoMingSubmitData.class);
            ToolBean.info("转换的submitData:"+submitData.getAddress());

            WxBaoming wxBaoming = new WxBaoming();

            try{

                //校验nonce
                ResultInfo ResultInfoCheckNonce = new ResultInfo();
                ResultInfoCheckNonce = tApiNonceService.checkNonce(submitData.getNonceMs(),loginId,submitData.getNonceZhi(),"报名新增！");

                if (ResultInfoCheckNonce.getCode()!=200)
                {
                    return ResultInfoCheckNonce;
                }


                Long sl = getBaseMapper().selectCount(new QueryWrapper<WxBaoming>().eq("sfzhm", Url.encrypt(submitData.getIdCard())));

                if(sl>0)  return new ResultInfo(500,"该身份证已经有报名信息！",null);



                if (null!=file){
                    for (MultipartFile wj : file) {
                        ToolBean.info("wj:"+wj);
                        if (StringUtils.isEmpty(wj.getOriginalFilename())){
                            continue;
                        }
                        ToolBean.info("wj:"+wj);
                        Long fileId= fileService.uploadFile(wj,loginId);

                        wxBaoming.setQmId(fileId);

                    }
                }else{
                    return new ResultInfo(500,"没有获取到签名信息！",null);
                }

                if (wxBaoming.getQmId()==null) return new ResultInfo(500,"没有获取到签名信息！",null);
                wxBaoming.setJmlx(submitData.getJmlx());
                wxBaoming.setXm(submitData.getName());
                wxBaoming.setXb(String.valueOf(submitData.getGender()));
                wxBaoming.setSfzhm(Url.encrypt(submitData.getIdCard()));
                wxBaoming.setSfzh8w(ToolBean.maskIdCard(submitData.getIdCard()));
                wxBaoming.setSjhm(Url.encrypt(submitData.getPhone()));
                wxBaoming.setSjhh6w(ToolBean.maskPhone(submitData.getPhone()));
                wxBaoming.setDzyx(submitData.getEmail());
                wxBaoming.setTRegionId(Long.parseLong(String.valueOf(submitData.getRegionId())));
                wxBaoming.setDz(submitData.getAddress());
                wxBaoming.setBslxId(Long.parseLong(String.valueOf(submitData.getCompetitionTypeId())));
                wxBaoming.setJmmc(submitData.getProgramName());
                wxBaoming.setJmsc(Integer.parseInt(submitData.getProgramDuration()));
                wxBaoming.setCsrs(Integer.parseInt(submitData.getParticipantCount()));
                wxBaoming.setTtmc(submitData.getGroupName());
                wxBaoming.setTtfzr(submitData.getGroupLeaderInfo());
                wxBaoming.setBdwd(Long.parseLong(String.valueOf(submitData.getPostOfficeId())));
                //这里记得明天修复！
                wxBaoming.setSfcyk(submitData.getHasPostCard());
                wxBaoming.setSfjsgh(submitData.getAcceptWealthService());
                wxBaoming.setJkgz(submitData.getHealthStatus());
                wxBaoming.setJjlxr(submitData.getEmergencyName());

                wxBaoming.setJjlxrSjhm(Url.encrypt(submitData.getEmergencyPhone()));
                wxBaoming.setJjlxrSjhh6w(ToolBean.maskPhone(submitData.getEmergencyPhone()));
                wxBaoming.setLyqd(Long.parseLong(String.valueOf(submitData.getSourceChannelId())));
                wxBaoming.setHyxxLsh(Long.parseLong(loginId));

                getBaseMapper().insert(wxBaoming);

                if (submitData.getJmlx().equals("2")){
                    List<TeamMember> teamMemberList = submitData.getTeamMembers();
                    for (TeamMember member : teamMemberList) {
                        // 获取成员信息
                        WxBaomingCyxx wxBaomingCyxx =new WxBaomingCyxx();
                        wxBaomingCyxx.setBmxxId(wxBaoming.getId());
                        wxBaomingCyxx.setCyxxId(Long.parseLong(String.valueOf(member.getId())));
                        wxBaomingCyxxMapper.insert(wxBaomingCyxx);
                    }
                }

                ResultInfo resultInfo = new ResultInfo(200, "新增成功！",null);
                return backRtn(resultInfo,loginId);


            }catch (Exception e){
                e.printStackTrace();
                throw new RuntimeException("报名失败！");
            }
        }
    }

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        try{
            JSONObject jsonObject = getData(map,loginId);
            if (StringUtils.isEmpty(loginId)){
                return new ResultInfo(500,"用户信息丢失！",null);
            }else{

                List<WxBaoming> wxBaomingList = getBaseMapper().selectList(new QueryWrapper<WxBaoming>().eq("hyxx_lsh",loginId));

                if (wxBaomingList != null && !wxBaomingList.isEmpty()) {
                    // 循环遍历列表，修改目标属性
                    for (WxBaoming baoming : wxBaomingList) {
                        String sjhm = baoming.getSjhm();
                        sjhm = Url.decrypt(sjhm);
                        baoming.setSjhm(sjhm);
                    }
                }

                //返回前端的内容
                Map<String,Object> rtnMap = new HashMap<>();
                rtnMap.put("wxBaomingList",wxBaomingList);

                ResultInfo resultInfo = new ResultInfo(200, "成功返回！",rtnMap);
                return backRtn(resultInfo,loginId);
            }
        }catch (Exception e){
            e.printStackTrace();
            ResultInfo resultInfo = new ResultInfo(500, "成功返回！",null);
            return backRtn(resultInfo,loginId);
        }

    }

    @Override
    public ResultInfo del(String loginId, Map<String, Object> map) {
        try{
            JSONObject jsonObject = getData(map,loginId);
            if (StringUtils.isEmpty(loginId)){
                return new ResultInfo(500,"用户信息丢失！",null);
            }else{
                String id="";
                if (jsonObject.containsKey("id")) id=jsonObject.getString("id");

                if (StringUtils.isEmpty(id)){
                    ResultInfo resultInfo = new ResultInfo(500, "信息丢失，无法删除！",null);
                    return backRtn(resultInfo,loginId);
                }

                WxBaoming wxBaoming = getBaseMapper().selectById(id);

                if (null==wxBaoming){
                    ResultInfo resultInfo = new ResultInfo(500, "报名信息不存在，无法删除！",null);
                    return backRtn(resultInfo,loginId);
                }

                if (String.valueOf(wxBaoming.getHyxxLsh()).equals(loginId)){
                    getBaseMapper().deleteById(id);
                    wxBaomingCyxxMapper.delete(new QueryWrapper<WxBaomingCyxx>().eq("bmxx_id",id));
                    ResultInfo resultInfo = new ResultInfo(200, "删除成功！",null);
                    return backRtn(resultInfo,loginId);
                }else{
                    ResultInfo resultInfo = new ResultInfo(500, "不能删除非自己填写的报名信息！",null);
                    return backRtn(resultInfo,loginId);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            ResultInfo resultInfo = new ResultInfo(500, "成功返回！",null);
            return backRtn(resultInfo,loginId);
        }

    }
    public ResultInfo index(String loginId, Map<String, Object> map) {
        try{
            JSONObject jsonObject = getData(map,loginId);
            if (StringUtils.isEmpty(loginId)){
                return new ResultInfo(500,"用户信息丢失！",null);
            }else{

                List<WxBaomingTj> wxBaomingTjList = wxBaomingTjMapper.selectList(new QueryWrapper<WxBaomingTj>().eq("state","1").orderByAsc("xh"));

                //返回前端的内容
                Map<String,Object> rtnMap = new HashMap<>();
                rtnMap.put("wxBaomingTjList",wxBaomingTjList);

                ResultInfo resultInfo = new ResultInfo(200, "成功返回！",rtnMap);
                return backRtn(resultInfo,loginId);
            }
        }catch (Exception e){
            e.printStackTrace();
            ResultInfo resultInfo = new ResultInfo(500, "成功返回！",null);
            return backRtn(resultInfo,loginId);
        }
    }

    //获取推荐背景图片
    public byte[] getTjbj(String id) {
        String wj = null;
        String basePath;

        // 确定基础路径
        String os = System.getProperty("os.name");
        if (os != null && os.contains("Windows")) {
            basePath = "d:\\wx\\tjbj\\";
        } else {
            basePath = "/home/wx/tjbj/";
        }

        try {
            // 尝试从数据库获取文件名
            WxBaomingTj wxBaomingTj = wxBaomingTjMapper.selectById(id);
            if (wxBaomingTj != null) {
                wj = wxBaomingTj.getBjdz();
            }
        } catch (Exception e) {
            // 发生任何异常都忽略，使用默认文件
            // 可以添加日志记录: log.warn("获取数据库记录异常，将使用默认文件", e);
        }

        // 尝试读取文件（先尝试原始文件，失败则用默认文件）
        return readFile(basePath, wj);
    }
    // 抽取文件读取逻辑为单独方法
    private byte[] readFile(String basePath, String fileName) {
        // 如果原始文件名不存在或无效，直接使用默认文件
        if (fileName == null || fileName.trim().isEmpty()) {
            fileName = "mrfm.png";
        }

        File file = new File(basePath + fileName);
        // 如果文件不存在，尝试默认文件
        if (!file.exists() || !file.isFile()) {
            fileName = "mrfm.png";
            file = new File(basePath + fileName);
            // 如果默认文件也不存在，返回null
            if (!file.exists() || !file.isFile()) {
                return null;
            }
        }

        // 读取文件内容
        try (FileInputStream inputStream = new FileInputStream(file)) {
            byte[] bytes = new byte[(int) file.length()];
            int bytesRead = inputStream.read(bytes);
            if (bytesRead == file.length()) {
                return bytes;
            }
        } catch (Exception e) {
            // 读取文件发生异常，返回null
            // 可以添加日志记录: log.error("读取文件异常", e);
        }

        return null;
    }

}
